package com.luocc.ccdemo.interceptor

import android.content.Context
import okhttp3.Interceptor
import okhttp3.Response

class AddCookieInterceptor(private val context: Context) : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val builder = request.newBuilder()
        val cookie = getCookie(request.url.host)
        if (!cookie.isNullOrEmpty()) {
            builder.addHeader("Cookie", cookie)
        }
        return chain.proceed(builder.build())
    }

    private fun getCookie(host: String): String? {
        val sp = context.getSharedPreferences("user", Context.MODE_PRIVATE)
        return sp.getString(host, "")
    }
}